package org.fastiot.data.sampling

class Latest {

    static mapWith = "mongo"

    Integer packetCode
    String hexPacketCode
    String terminalCode
    Date dateAcquired

    Map<String, Serializable> metadata
    Map<String, Serializable> contents

    Date dateCreated
    Date lastUpdated

    static embedded = ['metadata', 'contents']
    static transients = ['hexPacketCode']

    static constraints = {
        packetCode(nullable: false)
        hexPacketCode(blank: false)
        terminalCode(blank: false)
        dateAcquired(nullable: false)
        metadata(nullable: false)
        contents(nullable: false)
        dateCreated()
        lastUpdated()
    }

    static mapping = {
        version false
        collection "latestSampling"
        compoundIndex terminalCode: 1, packetCode: 1, dateAcquired: -1
    }

    def beforeValidate() {
        if (packetCode && !hexPacketCode)
            hexPacketCode = Integer.toHexString(packetCode)
        else if (hexPacketCode && !packetCode)
            packetCode = Integer.parseInt(hexPacketCode, 16)
    }

    def afterLoad() {
        if (packetCode)
            hexPacketCode = Integer.toHexString(packetCode)
    }
}
